﻿// 注释

using EVE.ECS_Model.Client.BCR;
using EVE.ECS_Model.Client.ECS;
using EVE.ECS_Model.Client.HK;
using EVE.ECS_Model.Client.PLC;
using EVE.ECS_Model.Client.Statistic;
using EVE.ECS_Model.Contract;
using EVE.ECS_Model.Server.Config;
using EVE.ECS_Model.Server.Process;
using EVE.ECS_Model.Server;
using GeneralCommon.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.EcsWeb.Option;
using Furion;
using Furion.DependencyInjection;
using GeneralCommon.Models.Connect;
using GeneralCommon.Models.Server;
using Furion.RemoteRequest.Extensions;

namespace Admin.EcsWeb.Service.Grpc;
public class GrpcService : IGrpcService
{
    private IGrpcChannelService _channelService;
    private IGroupDataGrpcService _groupDataGrpcService;
    private IConnectGrpcService _connectGrpcService;
   
    public GrpcService(IGrpcChannelService grpcChannelService)
    {
        _channelService = grpcChannelService;
      
    }
    /// <summary>
    /// 创建Grpc数据服务
    /// </summary>
    /// <returns></returns>
    private async Task CreateDataGrpcService()
    {

        if (_groupDataGrpcService == null || !_channelService.IsConnect)
        {
            _groupDataGrpcService = await _channelService.CreateGrpcService<IGroupDataGrpcService>(App.GetOptions<GrpcOptions>().ServerUrl);
        }
    }
    /// <summary>
    /// 创建Grpc连接服务
    /// </summary>
    /// <returns></returns>
    private async Task CreateConnectGrpcService()
    {
        if (_connectGrpcService == null || !_channelService.IsConnect)
        {
            _connectGrpcService = await _channelService.CreateGrpcService<IConnectGrpcService>(App.GetOptions<GrpcOptions>().ServerUrl);
        }
    }
    /// <summary>
    /// 获取PLC数据
    /// </summary>
    /// <param name="searchPlc"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<List<PushPlcGroup>>> GetPushGroups(SearchPlcModel searchPlc)
    {
        try
        {

            await CreateDataGrpcService();
            var gprcReturn = await _groupDataGrpcService.GetPushGroups(searchPlc);
            return gprcReturn;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<PushPlcGroup>>
            {
                Msg = ex.Message
            };
        }

    }
    /// <summary>
    /// 获取充放电预约任务
    /// </summary>
    /// <returns></returns>
    public async Task<GrpcReturn<List<HkWriteInfo>>> GetFmtAppoints()
    {
        try
        {

            await CreateDataGrpcService();
            var gprcReturn = await _groupDataGrpcService.GetFMTAppoints();
            return gprcReturn;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<HkWriteInfo>>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 删除预约缓存数据
    /// </summary>
    /// <param name="write"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<string>> RemoveFmtAppint(HkWriteInfo write)
    {
        try
        {

            await CreateDataGrpcService();
            var gprcReturn = await _groupDataGrpcService.DeleteFMTAppoint(write);
            return gprcReturn;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<string>
            {
                Msg = ex.Message
            };
        }
    }

    /// <summary>
    /// 获取Bcr数据
    /// </summary>
    /// <param name="searchPlc"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<List<PushBcrGroup>>> GetBcrGroups(SearchPlcModel searchPlc)
    {
        try
        {

            await CreateDataGrpcService();
            var gprcReturn = await _groupDataGrpcService.GetBcrPushGroups(searchPlc);
            return gprcReturn;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<PushBcrGroup>>
            {
                Msg = ex.Message
            };
        }

    }

    /// <summary>
    /// 获取Hk数据
    /// </summary>
    /// <param name="searchPlc"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<List<PushHKGroup>>> GetHkGroups(SearchPlcModel searchPlc)
    {
        try
        {

            await CreateDataGrpcService();
            var gprcReturn = await _groupDataGrpcService.GetHkPushGroups(searchPlc);
            return gprcReturn;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<PushHKGroup>>
            {
                Msg = ex.Message
            };
        }

    }
    /// <summary>
    /// 清除fmt缓存
    /// </summary>
    /// <param name="groupNum"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<string>> DeleteFmtCache(int groupNum)
    {
        try
        {

            await CreateDataGrpcService();
            var gprcReturn = await _groupDataGrpcService.DeleteFMTCaches(new SearchPlcModel
            {
                GroupNum = groupNum
            });
            return gprcReturn;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<string>
            {
                Msg = ex.Message
            };
        }
    }

    /// <summary>
    /// 获取设备的UnitTags数据
    /// </summary>
    /// <param name="searchUnit"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<List<ECSUnitTag>>> GetUnitTags(SearchUnitModel searchUnit)
    {
        try
        {

            await CreateDataGrpcService();
            var tags = await _groupDataGrpcService.GetECSUnitTags(searchUnit);
            return tags;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<ECSUnitTag>>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 获取输送线CV数据
    /// </summary>
    /// <param name="searchUnit"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<List<EcsCvUnit>>> GetCvUnits(SearchUnitModel searchUnit)
    {
        try
        {

            await CreateDataGrpcService();
            var tags = await _groupDataGrpcService.GetEcsCvUnits(searchUnit);
            return tags;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<EcsCvUnit>>
            {
                Msg = ex.Message
            };
        }
    }

    /// <summary>
    /// 获取输送线SC数据
    /// </summary>
    /// <param name="searchUnit"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<List<EcsScUnit>>> GetScUnits(SearchUnitModel searchUnit)
    {
        try
        {

            await CreateDataGrpcService();
            var tags = await _groupDataGrpcService.GetEcsScUnits(searchUnit);
            return tags;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<EcsScUnit>>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 获取注册的客户端配置
    /// </summary>
    /// <param name="id"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<SignClient>> ConnectAsync(int id, string name)
    {
        try
        {
            await CreateConnectGrpcService();
            var rs = await _connectGrpcService.ConnectAsync(new EVE.ECS_Model.Server.Config.SignClient
            {
                ClientID = id,
                Name = name
            });
            // 强制性把 DataServerUrl赋值
            if (rs.IsSuccess)
            {
                rs.Data.ServerUrl = AppSettings.GetValue("GrpcServer");
            }
            return rs;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<SignClient>
            {
                Msg = ex.Message
            };
        }



    }


    /// <summary>
    /// 发送扫码枪读取
    /// </summary>
    /// <param name="searchPlc"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<bool>> SendBcrRead(SearchPlcModel searchPlc)
    {
        try
        {
            await CreateDataGrpcService();

            var result = await _groupDataGrpcService.PushWriteBCR(new List<BCRWriteInfo>
            {
                new BCRWriteInfo
                {
                    GroupNumber=searchPlc.GroupNum,
                    IsTriger1Layer=true
                }
            });
            return result;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<bool>
            {
                Msg = ex.Message
            };
        }
    }


    /// <summary>
    /// 发送输送线写入数据
    /// </summary>
    /// <param name="datas"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<bool>> SendCvWrite(List<PlcCVAddr> datas)
    {
        try
        {
            if (datas == null || datas.Count == 0) return new GrpcReturn<bool>();
            await CreateDataGrpcService();

            var result = await _groupDataGrpcService.PushCVAddr(datas);

            return result;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<bool>
            {
                Msg = ex.Message
            };
        }
    }

    /// <summary>
    /// 发送堆垛机写入数据
    /// </summary>
    /// <param name="datas"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<bool>> SendScWrite(List<PlcSCAddr> datas)
    {
        try
        {
            if (datas == null || datas.Count == 0) return new GrpcReturn<bool>();
            await CreateDataGrpcService();

            var result = await _groupDataGrpcService.PushSCAddr(datas);

            return result;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<bool>
            {
                Msg = ex.Message
            };
        }
    }

    /// <summary>
    /// 发送杭可设备写入数据
    /// </summary>
    /// <param name="write"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<bool>> SendHkWrite(HkWriteInfo write)
    {
        try
        {

            await CreateDataGrpcService();

            var result = await _groupDataGrpcService.PushHkCommands(new List<HkWriteInfo>
                {
                    write
                });

            return result;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<bool>
            {
                Msg = ex.Message
            };
        }
    }

    /// <summary>
    /// 获取统计信息
    /// </summary>
    /// <returns></returns>
    public async Task<GrpcReturn<List<GroupRunningData>>> GetGroupStatistic()
    {
        try
        {
            await CreateDataGrpcService();
            var tags = await _groupDataGrpcService.GetGroupStatistic();
            return tags;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<GroupRunningData>>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 堆垛机入库
    /// </summary>
    /// <param name="job"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<GrpcReturn<string>> SendScEnterJob(ScEnterJob job)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.AddScEnterJob(job);


            return result;

        }
        catch (Exception ex)
        {
            return new GrpcReturn<string>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 堆垛机出库
    /// </summary>
    /// <param name="job"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<GrpcReturn<string>> SendScOutJob(ScOutJob job)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.AddScOutJob(job);
            return result;
        }
        catch (Exception ex)
        {
            return new GrpcReturn<string>
            {
                Msg = ex.Message
            };
        }
    }

    /// <summary>
    /// 获取入库任务
    /// </summary>
    /// <param name="scNum"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<List<ScEnterJob>>> GetEnterJobs(int scNum)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.GetEnterJobs(new SearchPlcModel
            {
                GroupNum = scNum
            });

            return result;

        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<ScEnterJob>>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 获取出库任务
    /// </summary>
    /// <param name="scNum"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<List<ScOutJob>>> GetOutJobs(int scNum)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.GetOutJobs(new SearchPlcModel
            {
                GroupNum = scNum
            });

            return result;

        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<ScOutJob>>
            {
                Msg = ex.Message
            };
        }
    }

    /// <summary>
    /// 获取移库任务
    /// </summary>
    /// <param name="scNum"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<List<ScMoveJob>>> GetMoveJobs(int scNum)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.GetMoveJobs(new SearchPlcModel
            {
                GroupNum = scNum
            });

            return result;

        }
        catch (Exception ex)
        {
            return new GrpcReturn<List<ScMoveJob>>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 移除入库任务
    /// </summary>
    /// <param name="scNum"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<GrpcReturn<string>> RemoveEnterJob(ScEnterJob scNum)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.RemoveEnterJob(scNum);

            return result;

        }
        catch (Exception ex)
        {
            return new GrpcReturn<string>
            {
                Msg = ex.Message
            };
        }
    }

    /// <summary>
    /// 移除移库任务
    /// </summary>
    /// <param name="scNum"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<string>> RemoveMoveJob(ScMoveJob scNum)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.RemoveMoveJob(scNum);

            return result;

        }
        catch (Exception ex)
        {
            return new GrpcReturn<string>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 完成移库任务
    /// </summary>
    /// <param name="scNum"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<string>> CompleteMoveJob(ScMoveJob scNum)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.CompleteMoveJob(scNum);

            return result;

        }
        catch (Exception ex)
        {
            return new GrpcReturn<string>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 移除出库任务
    /// </summary>
    /// <param name="scNum"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<GrpcReturn<string>> RemoveOutJob(ScOutJob scNum)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.RemoveOutJob(scNum);

            return result;

        }
        catch (Exception ex)
        {
            return new GrpcReturn<string>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 完成入库
    /// </summary>
    /// <param name="scNum"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<GrpcReturn<string>> CompleteEnterJob(ScEnterJob scNum)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.CompleteEnterJob(scNum);

            return result;

        }
        catch (Exception ex)
        {
            return new GrpcReturn<string>
            {
                Msg = ex.Message
            };
        }
    }
    /// <summary>
    /// 完成出库
    /// </summary>
    /// <param name="scNum"></param>
    /// <returns></returns>
    public async Task<GrpcReturn<string>> CompleteOutJob(ScOutJob scNum)
    {
        try
        {
            await CreateDataGrpcService();
            var result = await _groupDataGrpcService.CompleteOutJob(scNum);

            return result;

        }
        catch (Exception ex)
        {
            return new GrpcReturn<string>
            {
                Msg = ex.Message
            };
        }
    }

    /// <summary>
    /// 控制设备
    /// </summary>
    /// <param name="groupData"></param>
    /// <returns></returns>
    public async Task<ReturnModel<string>> ControlEquip(ConnectGroupData groupData)
    {
        try
        {
            var url = $"{App.GetOptions<GrpcOptions>().GrpcApiUrl}/api/message/executeconnect";
            var result = await url.SetBody(groupData).PostAsAsync<ReturnModel<string>>();

            return result;

        }
        catch (Exception ex)
        {
            return new ReturnModel<string>
            {
                Msg = ex.Message
            };
        }
    }

}
